import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:fsuper/fsuper.dart';

class MorePage extends StatefulWidget {
  @override
  _MorePageState createState() => _MorePageState();
}

class _MorePageState extends State<MorePage> {
  List _myTabs = [];
  bool _isEdit = false;

  @override
  void initState() {
    super.initState();
    _iniTabs();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1,
        backgroundColor: Theme.of(context).canvasColor,
        title: Text('更多', style: TextStyle(fontSize: 18)),
        centerTitle: true,
        actions: <Widget>[
          FlatButton(
            child: Text(
              _isEdit ? '保存' : '编辑',
              style: TextStyle(fontSize: 18),
            ),
            onPressed: () {
              setState(() {
                _isEdit = !_isEdit;
              });
              if (!_isEdit) {
                List<String> tabs = List<String>();
                _myTabs.forEach((value) {
                  tabs.add(json.encode(value));
                });
                SpUtils.put(SpUtils.SP_MYTAB, tabs);
                Toast.show("保存成功");
              }
            },
          )
        ],
      ),
      body: CustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(child: _classtifyWidget("常用功能", "（首页展示，最多七个）")),
          SliverGrid.count(
            crossAxisCount: 4,
            children: _myTabs.map((item) {
              return _toolWidget(item, true);
            }).toList(),
          ),
          SliverToBoxAdapter(child: _classtifyWidget("全部", "")),
          SliverGrid.count(
            crossAxisCount: 4,
            children: Comm.allToolTabs.map((item) {
              return _toolWidget(item, false);
            }).toList(),
          ),
        ],
      ),
    );
  }

  ///分类标签
  Widget _classtifyWidget(String name, String hint) {
    return FSuper(
      height: 36,
      textAlignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 20),
      spans: [
        TextSpan(text: name),
        TextSpan(
          text: hint,
          style: TextStyle(
            fontSize: 12,
            color: Color(0xffBBBBBB),
          ),
        ),
      ],
      textColor: Color(0XFF333333),
      textWeight: FontWeight.bold,
      textSize: 16,
      child1Alignment: Alignment.centerLeft,
      child1: Container(
        width: 6,
        height: 16,
        color: Theme.of(context).accentColor,
      ),
      child1Margin: EdgeInsets.only(left: 10, top: 1),
    );
  }

  ///工具类生成
  Widget _toolWidget(var item, bool isMy) {
    return FSuper(
      width: double.infinity,
      height: double.infinity,
      text: item['title'],
      textSize: 12,
      textWeight: FontWeight.w600,
      textAlignment: Alignment.bottomCenter,
      margin: EdgeInsets.all(10),
      child1: FSuper(
        width: 40,
        height: 40,
        backgroundColor: Color(item['color']),
        child1: Icon(Comm.iconMap[item['icon']], color: Colors.white),
        corner: Corner.all(20),
        shadowBlur: 4,
        shadowColor: Color(0xff999999),
      ),
      child1Margin: EdgeInsets.only(bottom: 6),
      onClick: () {
        if (!_isEdit) {
          var url = "${item['path']}";
          print('跳转链接：$url');
          Routers.router.navigateTo(
            context,
            url,
            transition: TransitionType.inFromRight,
          );
        }
      },
      child2: Icon(
        isMy ? Icons.remove_circle : Icons.add_circle,
        color: _isEdit ? Colors.black26 : Colors.transparent,
        size: 18,
      ),
      child2Alignment: Alignment.topRight,
      onChild2Click: () {
        if (_isEdit) {
          if (_myTabs.contains(item) && !isMy) {
            Toast.show("已添加过，请勿重复操作");
            return;
          }
          if (_myTabs.length == 7 && !isMy) {
            Toast.show("常用功能最多七个");
            return;
          }
          setState(() {
            if (isMy) {
              _myTabs.remove(item);
            } else {
              _myTabs.add(item);
            }
          });
        }
      },
    );
  }

  ///获取tab
  void _iniTabs() async {
    List<String> tmpTabs = await SpUtils.get(SpUtils.SP_MYTAB, List<String>());
    setState(() {
      _myTabs.clear();
      if (tmpTabs.isEmpty) {
        _myTabs.addAll(Comm.allToolTabs.sublist(0, 7));
      } else {
        tmpTabs.forEach((value) {
          _myTabs.add(json.decode(value));
        });
      }
    });
  }
}
